package com.rrd.itext.utils.pdf2Image;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import com.rrd.itext.utils.IOUtil;

public class ImageUtil {
    /**
     * @param image bytes, container height, container width
     * @return resized  image to fit in the container dimension such that it is not distorted
     * if height or width of the image are less the container size, 
     *      they should not be changed
     * If height, width or both are larger then container size,
     *      they should be reduced by a common higher of the two reduction factor calculated based on image height/container height and image width/container width.
     * @throws IOException 
     */
    public static byte[] adjustImage(byte[] imageByte, int containerWidth, int containerHeight) throws IOException{
        InputStream in = IOUtil.byteToInputStream(imageByte);
        BufferedImage src = ImageIO.read(in);
        int width = src.getWidth();
        int height = src.getHeight();
        if(width <= containerWidth && height <= containerHeight){
            return imageByte;
        }
        float rate = (width/(float)containerWidth) > (height/(float)containerHeight)?(width/(float)containerWidth):(height/(float)containerHeight);
        width = (int)(width / rate);
        height = (int)(height / rate);
        Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
        BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream();
        ImageIO.write(tag, "JPEG", imageOutputStream);
        return imageOutputStream.toByteArray();
    }
    
    public static void main(String args[]){
        try {
            byte[] src = IOUtil.inputStreamToByte(new FileInputStream(new File("D:\\DSC02630.JPG")));
            byte[] image = adjustImage(src, 1000, 500);
            IOUtil.bytes2File(image, "D:\\test.jpg");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
